<?php
/**
 * 蜗牛博客
 * 本文件内代码属于“蜗牛博客”项目，禁止修改再发布本程序源码，禁止去除页面底部的版权申明。所有版权保留
 * User: upliu
 * Email: 753073861@qq.com
 * QQ: 753073861
 * 程序主页：http://demo.upliu.net/snail-blog/
 */

require __DIR__.'/init.php';

check_login();

$db = Db::getInstance();

switch (get('action')) {
    case 'save':
        it_must_post();
        if ($id = post('id')) {
            $db->update('category', array(
                'name' => post('name'),
                'pid' => intval(post('pid')),
            ), 'id=?', $id);
            $msg = '保存分类成功';
        } else {
            $db->insert('category', array(
                'name' => $_POST['name'],
                'pid' => intval(post('pid')),
            ));
            $msg = '添加新分类成功';
        }
        redirect_path('category.php', $msg);
        break;


    case 'delete':
        it_must_post();
        $id = get('id');
        if ($id == CATEGORY_ID_DEFAULT) {
            redirect_path('category.php', '', '默认分类禁止删除');
        }
        if ($db->query("select 1 from category where pid=?", $id)) {
            redirect_path('category.php', '', '该分类下面还存在子分类，禁止删除');
        }
        $db->delete('category', 'id=?', $id);
        $count = $db->update('post', array('category_id' => CATEGORY_ID_DEFAULT), 'category_id=?', $id);
        if ($count > 0) {
            $db->execute("update category set item_count=item_count-$count where id=?", $id);
            $db->execute("update category set item_count=item_count+$count where id=?", CATEGORY_ID_DEFAULT);
            $extra_msg = "，原分类下{$count}篇文章已移至默认分类";
        } else {
            $extra_msg = '';
        }
        redirect_path('category.php', "删除分类成功$extra_msg");
        break;


    case 'edit':
    case 'add':
        if ($id = get("id")) {
            $category = $db->query('select * from category where id=?', $id);
        } else {
            $category = array();
        }
        if ($pid = get('pid')) {
            $category['pid'] = $pid;
        }
        echo renderWithLayout('category-form', array('category' => $category));
        break;


    default:
        $categorys = $db->queryAll("select * from category");
        $categorys = tree($categorys);
        echo renderWithLayout('category', array(
            'categorys' => $categorys,
        ));
        break;
}